package com.xzc.kafka.action.consumer;

import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.WakeupException;

import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicLong;

public class _1DBStoreOffset {

    public static void main(String[] args) {
        String topicName = "test-topic1";

        String groupID = "test-group";
        Properties props = new Properties();
        props.put("bootstrap.servers", "es1:19092,es2:19092,es3:19092");
        props.put("group.id", groupID);
//        props.put("enable.auto.commit", true);
        props.put("enable.auto.commit", false);
        props.put("auto.offset.reset", "earliest");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);

        final AtomicLong totalRebalanceTimeMs = new AtomicLong(0L);
        final AtomicLong joinStart = new AtomicLong(0L);
        consumer.subscribe(Arrays.asList(topicName), new ConsumerRebalanceListener() {
            @Override
            public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
                for (TopicPartition tp : partitions) {
                    //saveOffsetIntoDB(consumer.position(tp));
                }
                joinStart.set(System.currentTimeMillis());
            }

            @Override
            public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
                totalRebalanceTimeMs.addAndGet(System.currentTimeMillis() - joinStart.get());
                for (TopicPartition tp : partitions) {
                    //consumer.seek(tp,readOffsetFromExternalStore(tp));
                }
            }
        });
        try {
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Long.MAX_VALUE);
                for (ConsumerRecord<String, String> record : records) {
                    System.out.printf("topic = %s, partition=%d, offset=%d\n",
                            record.topic(),
                            record.partition(),
                            record.offset());
                }
            }
        } catch (WakeupException e) {
        } finally {
            System.out.println("Total rebalance time(ms): " + totalRebalanceTimeMs.get());
            consumer.close();
        }
    }
}
